"""
示例使用脚本 - 演示如何使用API自动化测试系统
"""
import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from main import APITestSystem
from src.metadata.metadata_manager import metadata_manager
from src.ai.test_case_generator import test_case_generator
from utils.logger import app_logger

def example_basic_usage():
    """基本使用示例"""
    print("=" * 60)
    print("基本使用示例")
    print("=" * 60)
    
    # 创建系统实例
    system = APITestSystem()
    
    # 初始化系统
    print("1. 初始化系统...")
    if not system.initialize():
        print("系统初始化失败，请检查配置")
        return
    
    # 显示系统状态
    print("\n2. 系统状态:")
    status = system.get_system_status()
    for key, value in status.items():
        print(f"   {key}: {value}")
    
    print("\n系统已准备就绪！")
    
    # 注意：以下示例需要实际的接口配置
    print("\n如需处理实际对象，请提供对象名称:")
    print("例如：system.process_object('User')")

def example_metadata_operations():
    """元数据操作示例"""
    print("\n" + "=" * 60)
    print("元数据操作示例")
    print("=" * 60)
    
    # 示例：手动创建元数据（用于测试）
    sample_schema = {
        "type": "object",
        "properties": {
            "id": {
                "type": "integer",
                "description": "用户ID"
            },
            "name": {
                "type": "string",
                "minLength": 2,
                "maxLength": 50,
                "description": "用户名"
            },
            "email": {
                "type": "string",
                "format": "email",
                "description": "邮箱地址"
            },
            "age": {
                "type": "integer",
                "minimum": 0,
                "maximum": 150,
                "description": "年龄"
            },
            "status": {
                "type": "string",
                "enum": ["active", "inactive", "pending"],
                "description": "用户状态"
            }
        },
        "required": ["name", "email"]
    }
    
    # 存储示例元数据
    print("1. 存储示例元数据...")
    success = metadata_manager.store_metadata("SampleUser", sample_schema)
    if success:
        print("✓ 元数据存储成功")
    else:
        print("✗ 元数据存储失败")
        return
    
    # 获取存储的元数据
    print("\n2. 获取存储的元数据...")
    metadata = metadata_manager.get_stored_metadata("SampleUser")
    if metadata:
        print(f"✓ 获取到 {len(metadata['fields'])} 个字段信息")
        for field in metadata['fields']:
            print(f"   - {field['field_name']}: {field['field_type']} "
                  f"({'必填' if field['is_required'] else '可选'})")
    else:
        print("✗ 获取元数据失败")

def example_ai_test_generation():
    """AI测试用例生成示例"""
    print("\n" + "=" * 60)
    print("AI测试用例生成示例")
    print("=" * 60)
    
    # 注意：这需要有效的OpenAI API Key
    print("1. 生成测试用例...")
    
    # 检查是否有OpenAI配置
    from config.config import settings
    if not settings.OPENAI_API_KEY or settings.OPENAI_API_KEY == "your_openai_api_key":
        print("⚠️  OpenAI API Key 未配置，跳过AI测试用例生成")
        print("   请在.env文件中设置 OPENAI_API_KEY")
        return
    
    # 生成测试用例
    success = test_case_generator.process_test_case_generation("SampleUser")
    if success:
        print("✓ AI测试用例生成成功")
        
        # 获取生成的测试用例
        test_cases = test_case_generator.get_test_cases("SampleUser")
        print(f"✓ 生成了 {len(test_cases)} 个测试用例")
        
        # 显示测试用例概览
        for i, case in enumerate(test_cases[:3], 1):  # 只显示前3个
            print(f"\n测试用例 {i}:")
            print(f"  名称: {case['case_name']}")
            print(f"  类型: {case['case_type']}")
            print(f"  场景: {case['scenario']}")
            print(f"  描述: {case['description']}")
    else:
        print("✗ AI测试用例生成失败")

def example_complete_workflow():
    """完整工作流程示例"""
    print("\n" + "=" * 60)
    print("完整工作流程示例")
    print("=" * 60)
    
    system = APITestSystem()
    
    # 初始化系统
    if not system.initialize():
        print("系统初始化失败")
        return
    
    # 处理示例对象
    print("1. 处理示例对象...")
    success = system.process_object("SampleUser")
    if success:
        print("✓ 对象处理成功")
        
        # 获取对象信息
        print("\n2. 获取对象完整信息...")
        object_info = system.get_object_info("SampleUser")
        if "error" not in object_info:
            print(f"✓ 对象名称: {object_info['object_name']}")
            print(f"✓ 字段数量: {len(object_info['metadata']['fields'])}")
            print(f"✓ 测试用例数量: {object_info['test_cases_count']}")
        else:
            print(f"✗ 获取对象信息失败: {object_info['error']}")
    else:
        print("✗ 对象处理失败")

def main():
    """主函数"""
    print("API自动化测试系统 - 使用示例")
    
    try:
        # 基本使用示例
        example_basic_usage()
        
        # 元数据操作示例
        example_metadata_operations()
        
        # AI测试用例生成示例
        example_ai_test_generation()
        
        # 完整工作流程示例
        example_complete_workflow()
        
        print("\n" + "=" * 60)
        print("示例演示完成！")
        print("=" * 60)
        
    except Exception as e:
        print(f"运行示例时发生错误: {str(e)}")
        app_logger.error(f"示例运行错误: {str(e)}")

if __name__ == "__main__":
    main() 